import * as echarts from '../../components/ec-canvas/echarts'
const app = getApp();
const domain = app.globalData.domain
let chart = null;
const formatDate = (num, fmt) => {

  if (num == '') {

    return ''

  }

  const date = new Date(num)

  let o = {

    "M+": date.getMonth() + 1, //月份

    "d+": date.getDate(), //日

    "h+": date.getHours(), //小时

    "m+": date.getMinutes(), //分

    "s+": date.getSeconds(), //秒

    "q+": Math.floor((date.getMonth() + 3) / 3), //季度

    "S": date.getMilliseconds() //毫秒

  };

  if (/(y+)/.test(fmt)) {

    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));

  }

  for (let k in o) {

    if (new RegExp("(" + k + ")").test(fmt)) {

      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

    }

  }

  return fmt;

}

function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { // 坐标轴指示器，坐标轴触发有效
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      },
      confine: true
    },
    // legend: {
    //   data: ['自控操作', '人工操作', '告警标识']
    // },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: [{
      type: 'category',
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      },
      data: new Array(25).fill(0).map((item, index) => index + ':00'),
    }],
    yAxis: [{
      type: 'value',
      axisTick: {
        show: false
      },
      data: new Array(20).fill(0).map(item => item + 1 + ':00'),
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      }
    }],
    series: [{
      type: 'bar',
      label: {
        normal: {
          // show: true,
          position: 'inside'
        }
      },
      data: [
        120,
        {
          value: 200,
          itemStyle: {
            color: '#B31111'
          }
        },
        150,
        80, {
          value: 200,
          itemStyle: {
            color: '#009B00'
          }
        },
        70,
        110,
        130,
        80,
        70,
        110,
        130, 80,
        70,
        110,
        130, 80,
        70,
        110,
        130, 80,
        70,
        110,
        130
      ],
      itemStyle: {
        emphasis: {
          color: '#072080'
        }
      }
    }, ]
  };

  chart.setOption(option);
  return chart;
}

function getOptions(data) {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { // 坐标轴指示器，坐标轴触发有效
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      },
      confine: true
    },
    // legend: {
    //   data: ['自控操作', '人工操作', '告警标识']
    // },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: [{
      type: 'category',
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      },
      data: new Array(25).fill(0).map((item, index) => index + ':00'),
    }],
    yAxis: [{
      type: 'value',
      axisTick: {
        show: false
      },
      data: new Array(20).fill(0).map(item => item + 1 + ':00'),
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      }
    }],
    series: [{
      type: 'bar',
      label: {
        normal: {
          // show: true,
          position: 'inside'
        }
      },
      data,
      itemStyle: {
        emphasis: {
          color: '#072080'
        }
      }
    }, ]
  };
}

// pages/data-detail/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ec: {
      // onInit: initChart,
      lazyLoad: true,
    },
    start: null,
    end: '日',
    startTime: '-1d',
    endTime: +new Date(),
    endString: '',
    datetimeVisible: false,
    datetime: null,
    currentTime: +new Date(),
    options: {},
    switchValue: false
  },
  handleChange(e) {
    console.log(e)
    this.setData({
      switchValue: e.detail.value
    })
    wx.request({
      url: `${domain}/admin-api/smc/things/scene/ctrl`,
      method: 'POST',
      data: {
        metricId: this.data.options.id,
        value: !e.detail.value ? 'OFF' : 'ON',
        func: 'write'
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.error === "Unauthorized") {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        if (res?.data.status == 200) {
          wx.showToast({
            title: '操作成功',
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  init_echarts: function (options, id) {
    // debugger
    //去获取echarts  这里的id就是echarts的id
    this.selectComponent(id).init((canvas, width, height, dpr) => {
      // 初始化图表
      let variable = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr, // 像素
      });
      variable.setOption(options);
      return variable //一定要return 否则展示会有问题
    });
  },
  onConfirm(e) {
    const {
      value
    } = e?.detail
    console.log(value)
    this.setData({
      currentTime: value
    }, () => {
      this.init(value)
    })
  },
  chooseTime() {
    this.setData({
      datetimeVisible: true
    })
  },
  changeEnd(e) {
    this.setData({
      end: e.target.dataset.type
    }, () => {
      this.init(this.data.startTime)
    })
  },
  init(startTime) {
    console.log('startTime', startTime)
    const currentTime = startTime || +new Date()
    const start = start || formatDate(currentTime, 'yyyy年MM月dd日')
    console.log(start)
    this.setData({
      start,
      startTime: currentTime
    })

    let end = currentTime
    if (this.data.end === '日') end = currentTime
    if (this.data.end === '周') end = currentTime + 3600000 * 24 * 7
    if (this.data.end === '月') end = currentTime + 3600000 * 24 * 30
    end = formatDate(end, 'yyyy年MM月dd日')
    console.log('end', end)
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: `${domain}/admin-api/smc/scene-metric/tsd`,
      method: 'GET',
      data: {
        start: formatDate(+new Date(startTime), 'yyyy-MM-dd'),
        endTime: formatDate(+new Date(startTime) + 86400000, 'yyyy-MM-dd'),
        // endTime: (+new Date(startTime) + 86400000) / 1000,
        // start: this.data.startTime,
        // end: this.data.endTime || '',
        metricId: this.data.options.id,
        dim: 'scene',
        valueType: 'avg',
        aggUnit: '60m'
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },

      success: res => {
        wx.hideLoading()
        if (res?.data?.error === "Unauthorized") {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        const alarms = res?.data?.data?.list?.[0]?.alarms.map(item => {
          item.date = formatDate(item.time, 'yyyy-MM-dd hh:mm:ss')
          return item
        })

        console.log('alarms', alarms)
        this.setData({
          endString: end,
          alarms
        })

        const alarmsTime = res?.data?.data?.list?.[0]?.alarms?.map(item => item.time) || []
        console.log('alarmsTime', alarmsTime)
        let dataList
        if (res?.data?.data?.list?.[0]?.details?.length === 0) {
          console.log('nodata')
          dataList = new Array(24).fill(0)
        } else {
          dataList = res?.data?.data?.list?.[0]?.details?.slice(0, 24) || []
          // dataList = dataList?.map(item => item.value?.toFixed(4))
          dataList = dataList?.map(item => {
            console.log('item.value', item.value)
            return {
              value: item.value?.toFixed(4),
              itemStyle: {
                color: alarmsTime?.includes(item.time) ? '#B31111' : '#072080'
              }
            }
          })

        }
        this.init_echarts(getOptions(dataList), '#echarts-pie')

      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      switchValue: options.value === 'ON',
      options
    }, () => {
      const currentDay = new Date().setHours(0, 0, 0, 0)
      this.init(+currentDay)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  onBack() {
    console.log(1)
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})